package com.spzx.channel.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.spzx.channel.config.ThreadPoolConfig;
import com.spzx.channel.domain.ItemVo;
import com.spzx.channel.service.ItemService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.domain.*;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * BelongProject: spzx-parent
 * BelongPackage: com.spzx.channel.service.impl
 * Description:
 *
 * @Author 段鑫涛
 * @Create 2025/5/29 11:21
 * @Version 1.0
 */
@Service
@Slf4j
public class ItemServiceImpl implements ItemService {

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public ItemVo item(Long skuId) {
        //远程调用商品微服务接口之前 提前知道用户访问商品SKUID是否存在与布隆过滤器
        String key = "sku:product:data";
        Boolean flag = redisTemplate.opsForValue().getBit(key, skuId);
        if (!flag) {
            log.error("用户查询商品sku不存在：{}", skuId);
            //查询数据不存在直接返回空对象
            throw new ServiceException("用户查询商品sku不存在");
        }

        ItemVo itemVo = new ItemVo();

        //获取sku信息
        CompletableFuture<ProductSku> skuCompletableFuture = CompletableFuture.supplyAsync(() -> {
            R<ProductSku> productSkuResult = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
            if (R.FAIL == productSkuResult.getCode()) {
                throw new ServiceException(productSkuResult.getMsg());
            }
            ProductSku productSku = productSkuResult.getData();
            itemVo.setProductSku(productSku);
            return  productSku;
        }, threadPoolExecutor);


        //获取商品信息
        CompletableFuture<Void> productCompletableFuture = skuCompletableFuture.thenAcceptAsync(productSku -> {
            Long productId = productSku.getProductId();
            R<Product> productResult = remoteProductService.getProduct(productId, SecurityConstants.INNER);
            if (R.FAIL == productResult.getCode()) {
                throw new ServiceException(productResult.getMsg());
            }
            Product product = productResult.getData();
            itemVo.setProduct(product);
            itemVo.setSliderUrlList(Arrays.asList(product.getSliderUrls().split(",")));
            itemVo.setSpecValueList(JSON.parseArray(product.getSpecValue()));
        }, threadPoolExecutor);


        //获取商品最新价格
        CompletableFuture<Void> skuPriceCompletableFuture = CompletableFuture.runAsync(() -> {
            R<SkuPrice> skuPriceResult = remoteProductService.getSkuPrice(skuId, SecurityConstants.INNER);
            if (R.FAIL == skuPriceResult.getCode()) {
                throw new ServiceException(skuPriceResult.getMsg());
            }
            itemVo.setSkuPrice(skuPriceResult.getData());
        }, threadPoolExecutor);


        //获取商品详情图片
        CompletableFuture<Void> productDetailsCompletableFuture = skuCompletableFuture.thenAcceptAsync(productSku -> {
            R<ProductDetails> productDetailsResult = remoteProductService.getProductDetails(productSku.getProductId(), SecurityConstants.INNER);
            if (R.FAIL == productDetailsResult.getCode()) {
                throw new ServiceException(productDetailsResult.getMsg());
            }
            List<String> detailsimagesUrlList = Arrays.asList(productDetailsResult.getData().getImageUrls().split(","));
            itemVo.setDetailsimagesUrlList(detailsimagesUrlList);
        }, threadPoolExecutor);


        //获取商品规格对应商品skuId信息
        CompletableFuture<Void> skuSpecValueCompletableFuture = skuCompletableFuture.thenAcceptAsync(productSku -> {
            R<Map<String, Long>> skuSpecValueResult = remoteProductService.getSkuSpecValue(productSku.getProductId(), SecurityConstants.INNER);
            if (R.FAIL == skuSpecValueResult.getCode()) {
                throw new ServiceException(skuSpecValueResult.getMsg());
            }
            itemVo.setSkuSpecValueMap(skuSpecValueResult.getData());
        }, threadPoolExecutor);


        //获取商品库存信息
        CompletableFuture<Void> skuStockCompletableFuture = CompletableFuture.runAsync(() -> {
            R<SkuStockVo> skuStockResult = remoteProductService.getSkuStock(skuId, SecurityConstants.INNER);
            if (R.FAIL == skuStockResult.getCode()) {
                throw new ServiceException(skuStockResult.getMsg());
            }
            itemVo.setSkuStockVo(skuStockResult.getData());
        }, threadPoolExecutor);

        // 等待所有任务完成
        CompletableFuture.allOf(
                skuCompletableFuture,
                productCompletableFuture,
                skuPriceCompletableFuture,
                productDetailsCompletableFuture,
                skuSpecValueCompletableFuture,
                skuStockCompletableFuture
        ).join();

        return itemVo;
    }
}
